package com.batsoft.trade.disruptor.opp;

import com.alibaba.fastjson.JSON;
import com.batsoft.trade.constant.Env;
import com.batsoft.trade.constant.HandleType;
import com.batsoft.trade.disruptor.account.AccountAdd;
import com.batsoft.trade.entity.HoldSpace;
import com.batsoft.trade.entity.OrderData;
import com.batsoft.trade.model.RedisKey;
import com.batsoft.trade.util.JedisUtil;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019/8/29 15:32
 */
@Slf4j
public class OppDataEventHandler implements WorkHandler<OppDataEvent> {

    private JedisUtil jedisUtil;

    public OppDataEventHandler(JedisUtil jedisUtil) {
        this.jedisUtil = jedisUtil;
    }

    // 账户操作
    private List<AccountAdd> accountAdds = new LinkedList<>();

    @Override
    public void onEvent(OppDataEvent event) {
        accountAdds.clear();
        Jedis jedis = jedisUtil.getJedis();
        Transaction transaction = jedis.multi();
        OppData oppData = event.getValue();
        OrderData oData = oppData.getOData();
        try {
            switch (oData.getHandleType()) {
                case BUY_OPEN_MORE:

                    break;
                case SELL_OPEN_EMPTY:   // 建仓
                    if (oData.getCount().compareTo(BigDecimal.ZERO) == 0) {
                        // 全部完成
                        calculateFee(oData, oppData.getCount());    // 手续费
                        transaction.hset(RedisKey.getMatchSuccessOrder(oppData.getCycle(), oData.getCoinCode()), oData.getOrderNum(), JSON.toJSONString(oData));
                        // 持仓统计

                        HoldSpace space = new HoldSpace();

                    } else {
                        // 部分完成

                    }
                    break;
                case SELL_FLAT_MORE:

                    break;
                case BUY_FLAT_EMPTY:   // 清仓


                    break;


                default:
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("对手计算失败~", e);
        }
        List<Object> exec = transaction.exec();
        if (exec.size() > 0) {
            log.info("队列消费成功");
        }
    }

    /**
     * 手续费计算0
     * (成交合约张数 * 合约面值 / 成交均价) * 费率
     */
    private void calculateFee(OrderData oData, BigDecimal dealCount) {
        BigDecimal mean = oData.getTotalMoney().divide(dealCount, Env.DECIMAL, BigDecimal.ROUND_DOWN);
        BigDecimal fee = dealCount.multiply(oData.getFaceValue()).divide(mean, Env.DECIMAL, BigDecimal.ROUND_DOWN).multiply(oData.getFeeRatio()).setScale(Env.DECIMAL, BigDecimal.ROUND_DOWN);
        accountAdds.add(new AccountAdd(oData.getUserId(), HandleType.FEE, fee.negate()));
    }
}
